var express = require('express');
var router = express.Router();

require('./../util/util.js');

var User = require("./../models/user.js")
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
//登录
router.post('/login', function(req, res, next) {
  var param = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  }
  User.findOne(param, function(err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      if (doc) {
        //保存到cookie
        res.cookie("userId", doc.userId, {
          path: '/',
          maxAge: 1000 * 60 * 60
        });
        res.cookie("userName", doc.userName, {
          path: '/',
          maxAge: 1000 * 60 * 60
        });
        res.json({
          status: '0',
          result: {
            userName: doc.userName,
          }
        })
      }
    }
  })
})
//退出
router.post('/logout', function(req, res, next) {
  //清空cookie
  res.cookie('userId', '', {
    path: '/',
    maxAge: -1
  });
  res.json({
    status: '0',
    msg: '退出成功',
    result: {}
  })
})
//验证是否登录
router.get('/checkLogin', function(req, res, next) {
  if (req.cookies.userId) {
    res.json({
      status: '0',
      msg: '',
      result: req.cookies.userName || ''
    })
  } else {
    res.json({
      status: '1',
      msg: '未登录',
      result: ''
    })
  }
});
//查询购物车中的商品数量
router.get('/getCartCount',function  (req,res,next) {
	if(req.cookies && req.cookies.userId){
		let userId = req.cookies.userId;
		User.findOne({"userId":userId},function  (err,doc) {
			if(err){
				res.json({
					status:'1',
					msg:err.message,
					result:''
				})
			}else{
				var cartList = doc.cartList;
				let cartCount = 0;
				cartList.forEach( function(item, index) {
					cartCount += parseInt(item.productNum)
				});
				res.json({
					status:'0',
					meg:'',
					result:cartCount
				})
			}
		})
	}
})
//购物车数据加载
router.get('/cartList', function(req, res, next) {
  var userId = req.cookies.userId;
  User.findOne({ userId: userId }, function(err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      if (doc) {
        res.json({
          status: '0',
          msg: '',
          result: doc.cartList
        })
      }
    }
  })
})
//删去购物车
router.post('/cartDel', function(req, res, next) {
  let userId = req.cookies.userId;
  let productId = req.body.productId;
  console.log(userId)
  console.log(productId)
  //删去数组中的某一条
  User.update({
    userId: userId
  }, {
    $pull: {
      "cartList": {
        "productId": productId
      }
    }
  }, function(err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      console.log(doc)
      res.json({
        status: '0',
        msg: '',
        result: "数据删去成功"
      })
    }
  });
});
//数量加减 更改选中
router.post('/cartEdit', function(req, res, next) {
  let userId = req.cookies.userId;
  let productId = req.body.productId;
  let productNum = req.body.productNum;
  let checked = req.body.checked;
  User.update({ "userId": userId, "cartList.productId": productId }, {
    "cartList.$.productNum": productNum,
    "cartList.$.checked": checked
  }, function(err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      console.log(doc)
      res.json({
        status: '0',
        msg: '',
        result: "数量更改成功"
      })
    }
  })
});
//全选
router.post('/editCheckAll', function(req, res, next) {
  let userId = req.cookies.userId;
  let checkAll = req.body.checkAll ? "1" : 0;
  User.findOne({ 'userId': userId }, function(err, userdoc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      if (userdoc) {
        userdoc.cartList.forEach(item => {
          item.checked = checkAll;
        })
        userdoc.save(function(err1, doc2) {
          if (err1) {
            res.json({
              status: '1',
              msg: err1.message,
              result: ''
            })
          } else {
            res.json({
              status: '0',
              msg: '更新成功',
              result: ''
            })
          }
        })
      }
    }
  })
});
//查询用户地址
router.get("/addressList",function  (req,res,next) {
	let userId = req.cookies.userId;
	User.findOne({"userId":userId},function(err,userdoc){
		if(err){
			res.json({
              status: '1',
              msg: err1.message,
              result: ''
            })
		}else{
			if(userdoc){
				res.json({
	              status: '0',
	              msg: "查询成功",
	              result: userdoc.addressList
            	})
			}
		}
	})
});
//设置默认地址
router.post('/setDefault',function(req,res,next) {
	let userId = req.cookies.userId;
	let addressId = req.body.addressId;
	User.findOne({userId:userId},function  (err,userdoc) {
		if(err){
			res.json({
              status: '1',
              msg: err1.message,
              result: ''
        	})
		}else{
			if(userdoc){
				userdoc.addressList.forEach(item=>{
					if(item.addressId == addressId){
						item.isDefault =true;
					}else{
						item.isDefault =false
					}
				});
				userdoc.save(function (err2,doc) {
					if(err2){
						res.json({
			              status: '1',
			              msg: err2.message,
			              result: ''
			        	});
					}else{
						res.json({
			              status: '0',
			              msg: '设置成功',
			              result: ''
			        	})
					}
				});
			};
		};
	});
})
//删去地址
router.post('/delAddress',function  (req,res,next) {
	let userId = req.cookies.userId;
	let addressId = req.body.addressId;
	User.update(
		{"userId":userId},
		{"$pull":
			{"addressList":
				{"addressId":addressId}
			}
		},function(err,doc){
			if(err){
				res.json({
	              status: '1',
	              msg: err.message,
	              result: ''
	        	});
	        }else{
	        	res.json({
	              status: '0',
	              msg: '删去地址成功',
	              result: doc
	        	});
	        }
		}
	)
});
//生成订单
router.post('/payMent',function(req,res,next){
	let userId = req.cookies.userId;
	let orderTotal = req.body.orderTotal;
	let addressId = req.body.addressId;
	User.findOne({"userId":userId},function(err,doc){
		if(err){
			res.json({
				status:"1",
				msg:err.message,
				result:''
			})
		}else{
			//获取当前用户选择的地址信息；
			let address = '';
			let goodsList = []
			doc.addressList.forEach(item=>{
				if(item.addressId == addressId){
					address = item
				}
			});
			//获取用户购物车中选择的商品；
			doc.cartList.forEach(item=>{
				if(item.checked =="1"){
					goodsList.push(item);
				}
			});
			//订单号
			var platform ='622';
			var r1 = Math.floor(Math.random()*10);
			var r2 = Math.floor(Math.random()*10);
			var sysDate = new Date().Format('yyyyMMddhhmmss')
			var createDate = new Date().Format('yyyy-MM-dd hh-mm-ss');
			var orderId = platform +r1+sysDate+r2
			//生成订单
			var order = {
				orderId:orderId,
				orderTotal:orderTotal,
				addressInfo:address,
				goodsList:goodsList,
				orderStatus:'1',
				createDate:createDate
			};
			doc.orderList.push(order);
			doc.save(function  (err2,doc2) {
				if(err2){
					res.json({
						status:"1",
						msg:err2.message,
						result:''
					})
				}else{
					res.json({
						status:'0',
						msg:'订单生成成功',
						result:{
							orderId:order.orderId,
							orderTotal:order.orderTotal,
							addressInfo:order.addressInfo
						}
					})
				}
			})
		}
	})
});
//根据订单id查询订单信息
router.get("/orderDetail",function  (req,res,next) {
	let userId = req.cookies.userId;
	let orderId = req.param('orderId');
	User.findOne({"userId":userId},function  (err,userInfo) {
		if(err){
			res.json({
				status:'1',
				msg:err.message,
				result:''
			})
		}else{
			let orderList = userInfo.orderList;
			if(orderList.length>0){
				let orderTotal = 0;
				let streetName =''
				orderList.forEach(item=>{
					if(item.orderId ==orderId){
						orderTotal = item.orderTotal;
						streetName = item.addressInfo.streetName
					}
				})
				if(orderTotal>0){
					res.json({
						status:'0',
						msg:'',
						result:{
							orderTotal:orderTotal,
							orderId:orderId,
							streetName:streetName
						}
					})
				}else{
					res.json({
						status:'120002',
						msg:'无此订单',
						result:''
					})
				}
			}else{
				res.json({
					status:'120001',
					msg:'当前还没有任何订单',
					result:''
				})
			}
		}
	})

})


module.exports = router;
